package com.requiem.hist_group_manage_springboot.service.impl;

import com.requiem.hist_group_manage_springboot.common.JWTUtil;
import com.requiem.hist_group_manage_springboot.constants.SystemConstants;
import com.requiem.hist_group_manage_springboot.exception.R;
import com.requiem.hist_group_manage_springboot.mapper.ManagerMapper;
import com.requiem.hist_group_manage_springboot.model.ManagerModel;
import com.requiem.hist_group_manage_springboot.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private JWTUtil jwtUtil;

    public R login(String username, String password) {
        String finalPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        ManagerModel manager = managerMapper.getManagerByUP(username, finalPassword);
        if (manager == null) {
            return R.error(SystemConstants.USERNAME_PASSWORD_ERROR, SystemConstants.USERNAME_PASSWORD_ERROR_MSG);
        } else {
            Map<String, Object> claims = new HashMap<>();
            claims.put("user_id", manager.getId());
            String token = jwtUtil.createToken(claims);
            Map<String, String> return_obj = new HashMap<>();
            return_obj.put("token", token);
            return R.success(return_obj);
        }
    }
}
